using QFramework;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.PlayerLoop;
using Spine.Unity;
using Spine;
using DG.Tweening;
using System;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;

public class SettlementManager : MonoBehaviour
{

    public GameObject JieSuanRoundRank;
    public Transform CanvasNode;

    public Transform TiAreaTransform;//用来播放正确答案的动画

    public JifenManager jifenManager;

    public GameObject YanHua; //用户头像播放的小烟花

    public GameObject LiHua;//正确率大于50%的时候的大礼花

    public GameObject DaAnDialogAnima;//播放答案的动画
    void Awake()
    {
        ReceiveSocket receiveSocket = FindObjectOfType<ReceiveSocket>();
        if (receiveSocket != null)
        {
            receiveSocket.OnRoundSettlementReceived +=  (data) => {
                // 处理回合结算
                if(data.round_id.ToString() == GlobalData.RoundId){
                    Debug.Log($"处理回合结算: {data.round_id}");
                    GameObject SPage = Instantiate(JieSuanRoundRank, CanvasNode);
                }
                
            };
        }
    }
    void Start()
    {
        if (jifenManager == null)
        {
            jifenManager = FindObjectOfType<JifenManager>();
            if (jifenManager == null)
            {
                Debug.LogWarning("SettlementManager: JifenManager not assigned or found!");
            }
        }
        //开始结算，还没有更新积分，靠这个事件更新积分 -- 有优化空间  TODO
         StringEventSystem.Global.Register(EventID.SingleJieSuanStart, (List<GameObject> studentsNodes) =>
            {
                if (studentsNodes == null)
                {
                    Debug.LogWarning("Received null studentsNodes in SingleJieSuanStart event");
                    return;
                }
                HandleSingleSettlement(studentsNodes);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

         StringEventSystem.Global.Register(EventID.ClassJieSuanStart, (List<GameObject> studentsNodes) =>
            {
                if (studentsNodes == null)
                {
                    Debug.LogWarning("Received null studentsNodes in ClassJieSuan event");
                    return;
                }
                HandleClassSettlement(studentsNodes);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

        //监听玩法结束画面
        StringEventSystem.Global.Register(EventID.GameOver,async ()=>{
            //先请求结算的接口，返回成功之后再显示结算画面
            bool res = await RoundSettlementAsync();
            if (!res)
            {
                Debug.Log("结算接口请求失败");
                return;
            }
            // ToastManager.Instance.ShowToast("结算成功");
            GameObject JSPage = Instantiate(JieSuanRoundRank, CanvasNode);
           
        }).UnRegisterWhenGameObjectDestroyed(gameObject);


        //积分算完之后，请求后台，更新积分
        StringEventSystem.Global.Register(EventID.SingleModeJifenOver, (List<GameObject> studentsNodes) =>
        {
            //单人赛
            _ = UpdateJiFenPoolNumAsync(studentsNodes);
        }).UnRegisterWhenGameObjectDestroyed(gameObject);
        StringEventSystem.Global.Register(EventID.ClassJifenOver, (List<GameObject> studentsNodes) =>
        {
            //班级
            _ = UpdateJiFenPoolNumAsync(studentsNodes);
        }).UnRegisterWhenGameObjectDestroyed(gameObject);

    }

    private void HandleSingleSettlement(List<GameObject> studentsNodes)
    {
       Debug.Log("单人赛单局结算逻辑");

       CreateTiAnsAreaInfo(studentsNodes);
       // 积分结算
       StringEventSystem.Global.Send(EventID.SingleJifenJieSuanStart, studentsNodes);
       
    }

     private void HandleClassSettlement(List<GameObject> studentsNodes)
    {
        Debug.Log("班级赛单局结算逻辑");

        //暂时没有区分AB班级
        CreateTiAnsAreaInfo(studentsNodes);
        
        //结算积分
        StringEventSystem.Global.Send(EventID.ClassJifenJieSuanStart, studentsNodes);
    }

    //计算本题 正确答案，答案解析，正确率等信息
    private void CreateTiAnsAreaInfo(List<GameObject> studentsNodes){
        CorrectAnswerStructure correctAnswerStructure = new();
       //获取正确答案
       int rightAnswer = PlayerPrefs.GetInt(GameMode.correctAnswer);

       int allAnswerNum = 0;
       int rightAnswerNum = 0;
        //遍历列表中每个学生的答案，并于正确答案做对比
        foreach (var student in studentsNodes)
        {
            //获取学生答案
            var studentAnswer = student.GetComponentInChildren<Student>().answer;
            if(student.GetComponentInChildren<Student>().getChiTiZhengQue() == true){
                studentAnswer = rightAnswer;
            }
            //比较学生答案与正确答案
            if (studentAnswer == rightAnswer)
            {
                student.GetComponentInChildren<Student>().incrementCorrectAnswers();
                rightAnswerNum += 1;
                //加一个烟花庆祝一下
                // 使用 DOTween 的延迟
                DOVirtual.DelayedCall(3f, () => {
                    // 在这里执行延迟后的操作
                   Instantiate(YanHua, student.transform);
                   
                });
                
            }
            if (studentAnswer != 0)
            {
                student.GetComponentInChildren<Student>().incrementCorrectAnswers();
                allAnswerNum += 1;
            }
        }

        Debug.Log("正确答案：" + rightAnswerNum);
        Debug.Log("答题总数：" + allAnswerNum);
        float rightAnswerRate = 0;
        //计算本题正确率
        if (rightAnswerNum == 0)
        {
            correctAnswerStructure.zhengQueLveText = "0%";
        }else{
            rightAnswerRate = (float)rightAnswerNum / allAnswerNum * 100;
            correctAnswerStructure.zhengQueLveText = rightAnswerRate.ToString("F1") + "%";
        }        
        
        correctAnswerStructure.rightAnswer = rightAnswer;
        Debug.Log("正确率：" + correctAnswerStructure.zhengQueLveText);
        
        
        //在这之前需要播放动画
        GameObject showAnsAni = Instantiate(DaAnDialogAnima, TiAreaTransform);
        SkeletonGraphic sp = showAnsAni.transform.Find("sp").GetComponent<SkeletonGraphic>();
        
        //延迟1秒显示答案
        DOVirtual.DelayedCall(1f, () => {
            StringEventSystem.Global.Send(EventID.ShowRightAnswer, correctAnswerStructure);
        });

        sp.AnimationState.Complete += (TrackEntry trackEntry) => {
            // if(rightAnswerRate > 50){
            //     Instantiate(LiHua, CanvasNode);
            // }
            showAnsAni.DestroySelfAfterDelay(1);
        };
        
    }

    private async Task<bool> UpdateJiFenPoolNumAsync(List<GameObject> studentsNodes)
    {
        try
        {
            var answers = new List<object>();
            foreach (var studentObj in studentsNodes)
            {
                var student = studentObj.GetComponentInChildren<Student>();
                var correct = 0;
                if(student.getAnswer() != 0){
                    if(student.getAnswer() == PlayerPrefs.GetInt(GameMode.correctAnswer)){
                        correct = 1;
                    }else{
                        correct = 0;
                    }
                    answers.Add(new {
                        id = student.getStudentID(), // 学生ID
                        score = student.GetSingleTiJifen(), // 学生得分
                        is_correct = correct, // 是否答对
                        group_id = student.getClassType() == 0 ? 1 : student.getClassType() // 分组ID
                    });
                }
                
            }

            var data = new {
                room_id  = GlobalData.RoomId,
                round_id = GlobalData.RoundId,
                question_id = GlobalData.TiIndex,
                answers = answers
            };
            var postResponse = await HttpClientService.Instance
                .Post("/round/questionSettlement")
                .SetBody(data)
                .SendAsync();
            
            if (!postResponse.IsSuccess)
            {
                print("结算请求失败");
                return false;
            }

            print("postResponse:" + postResponse.GetJson());
            // 解析JSON数据
            JieSuanResponse RspData = JsonUtility.FromJson<JieSuanResponse>(postResponse.GetJson());
            //判断status是否等于0
            if (RspData.status != 0)
            {
                print("结算请求失败");
                return false;
            }

            //循环清空singlejifen
            foreach (var studentObj in studentsNodes)
            {
                var student = studentObj.GetComponentInChildren<Student>();
                student.ResetAfterSingleTiSeletment();
            }
            return true;
        }
        catch (Exception ex)
        {
            print($"QueryTokenAsync异常: {ex.Message}");
            return false;
        }
    }

    private async Task<bool> RoundSettlementAsync()
    {
        ToastManager.Instance.ShowToast("结算中...");
        try
        {
            var data = new {
                room_id  = GlobalData.RoomId,
                round_id = GlobalData.RoundId,
                points_pool = jifenManager.GetJiFenPoolNum(),
            };
            var postResponse = await HttpClientService.Instance
                .Post("/round/roundSettlement")
                .SetBody(data)
                .SendAsync();
            
            if (!postResponse.IsSuccess)
            {
                print("结算请求失败");
                return false;
            }

            print("postResponse:" + postResponse.GetJson());
            // 解析JSON数据
            JieSuanResponse RspData = JsonUtility.FromJson<JieSuanResponse>(postResponse.GetJson());
            //判断status是否等于0
            if (RspData.status != 0)
            {
                print("结算请求失败");
                return false;
            }
            return true;
        }
        catch (Exception ex)
        {
            print($"QueryTokenAsync异常: {ex.Message}");
            return false;
        }
    }

} 

//*
// {
//     "status": 0,
//     "data": [
//         {
//             "status": 1
//         }
//     ]
// }
//生成新的 结构
[System.Serializable]
public class JieSuanResponse
{
    public int status;
    public JieSuanResponseData data;
}
[System.Serializable]
public class JieSuanResponseData
{
    public int status;
}
